<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Auth;
use think\Db;
use think\Exception;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
        $this->view->assign("levelList", $this->model->getLevelList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['company'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                // $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->visible(['id', 'nickname', 'username', 'level', 'gender', 'age', 'mobile', 'number', 'health', 'createtime', 'real', 'work_hour', 'work_times', 'status', 'company_id', 'company', 'health_image']);
                if($v->getRelation('company')){
                    $v->getRelation('company')->visible(['company_name']);
                }
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row                 = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids                 = $ids ? $ids : $this->request->post("ids");
        $row                 = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

    /**
     * 批量禁用/启用
     */
    public function batch()
    {
        $id  = input('ids', false);
        $act = input('act', false);

        if (!$id) $this->error('参数错误');
        if ($act === false) $this->error('参数错误');

        try {
            Db::startTrans();
            $result = $this->model->save(['status' => $act], ['id' => ['in', $id]]);

            if (!$result) {
                throw new Exception('未发生更改');
            }
            Db::commit();
            $this->success('操作成功');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 禁用
     */
    public function disable()
    {
        $id = input('ids', false);
        if (!$id) $this->error('参数错误');

        $row = $this->model->get($id);
        try {
            Db::startTrans();
            $result = $row->save(['status' => 2], ['id' => $id]);
            if (!$result) {
                throw new Exception('未发生更改');
            }
            Db::commit();
            $this->success('禁用成功');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 启用
     */
    public function enable()
    {
        $id = input('ids', false);
        if (!$id) $this->error('参数错误');

        $row = $this->model->get($id);
        try {
            Db::startTrans();
            $result = $row->save(['status' => 1], ['id' => $id]);
            if (!$result) {
                throw new Exception('未发生更改');
            }
            Db::commit();
            $this->success('启用成功');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 批量 设置分组（公司）
     */
    public function group()
    {
        $id         = input('ids', false);
        $company_id = input('company_id', false);

        if (!$id) $this->error('参数错误');
        if ($company_id == false) $this->error('请选择分组（公司）');

        try {
            Db::startTrans();
            $result = $this->model->save(['company_id' => $company_id], ['id' => ['in', $id]]);

            if (!$result) {
                throw new Exception('未发生更改');
            }
            Db::commit();
            $this->success('操作成功');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 批量 设置等级
     */
    public function level()
    {
        $id         = input('ids-level', false);
        $company_id = input('level', false);

        if (!$id) $this->error('参数错误');
        if ($company_id == false) $this->error('请选择等级');

        try {
            Db::startTrans();
            $result = $this->model->save(['level' => $company_id], ['id' => ['in', $id]]);

            if (!$result) {
                throw new Exception('未发生更改');
            }
            Db::commit();
            $this->success('操作成功');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }
}
